package cn.wky.cale.calculate.lex;

public class Lexer {

    private int index;
    private char[] expr;

    public enum TokenEnum {
        NUM,
        ADD,
        SUB,
        MUL,
        DIV
    }

    public static class TokenType {
        public TokenEnum tokenEnum;
        public double value;

        public TokenType(TokenEnum tokenEnum, double value) {
            this.tokenEnum = tokenEnum;
            this.value = value;
        }

        @Override
        public String toString() {
            return "TokenType{" +
                    "tokenEnum=" + tokenEnum +
                    ", value=" + value +
                    '}';
        }
    }

    public Lexer(String expr) {
        this.expr = expr.toCharArray();
        index = 0;
    }

    public TokenType getToken() {
        int status = 0;
        StringBuilder builder = new StringBuilder();
        while (index < expr.length) {
            char c = expr[index];
            if (status == 0 && c == '+') {
                index++;
                return new TokenType(TokenEnum.ADD, 0);
            } else if (status == 0 && c == '-') {
                index++;
                return new TokenType(TokenEnum.SUB, 0);
            } else if (status == 0 && c == '*') {
                index++;
                return new TokenType(TokenEnum.MUL, 0);
            } else if (status == 0 && c == '/') {
                index++;
                return new TokenType(TokenEnum.DIV, 0);
            }
            if (status == 0 && ('0' <= c && c <= '9')) {
                status = 1;
                builder.append(c);
                index++;
                continue;
            }
            if (status == 1) {
                if (c == '.' || '0' <= c && c <= '9') {
                    builder.append(c);
                    index++;
                    continue;
                }
                if (c == '+' || c == '-' || c == '*' || c == '/') {
                    return new TokenType(TokenEnum.NUM, Double.parseDouble(builder.toString()));
                }
            }
        }
        if (status == 1 && builder.length() > 0) {
            return new TokenType(TokenEnum.NUM, Double.parseDouble(builder.toString()));
        }
        return null;
    }
}
